package cn.xxm.scene.validate.aop;


import cn.xxm.scene.validate.annotation.Validate;
import cn.xxm.scene.validate.executor.ValidatorExecutor;
import cn.xxm.scene.validate.response.CommonResponseInfo;
import cn.xxm.scene.validate.response.FSResponseModel;
import cn.xxm.scene.validate.response.ValidatorResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;


@Aspect
@Component
public class ValidateAop {
    protected Logger logger =  LoggerFactory.getLogger(this.getClass());
	
    //@Autowired
    //private ValidatorExecuter validator;


	@Autowired
	private ValidatorExecutor validator;

	@Pointcut("(execution(public * cn.xxm.scene.controller..*.*(..)))")
	public void paramValidate(){}
	
	@Around("paramValidate()")
	public FSResponseModel<?> doParamValidate(ProceedingJoinPoint joinPoint) throws Throwable{
		logger.info("paramValidate->started");		
		FSResponseModel<?> model = null;
		ValidatorResult<?> result = isValid(joinPoint);//校验入参
		if(!result.isValid()){//参数校验不通过
			model = new FSResponseModel<Object>(result.getResponseInfo());
			logger.info("参数校验失败：msg:{}",result.getResponseInfo());
			return model;
		}
		model = (FSResponseModel<?>) joinPoint.proceed();
		logger.info("paramValidate->ended");	
		return model;
	}
	
	private ValidatorResult<?> isValid(ProceedingJoinPoint joinPoint){
		Signature signature = joinPoint.getSignature();
		ValidatorResult<?> result = new ValidatorResult<CommonResponseInfo>();
		Object [] args = joinPoint.getArgs();
		if(signature instanceof MethodSignature){
			MethodSignature methodSignature = (MethodSignature)signature;
			Annotation [] [] annotations = methodSignature.getMethod().getParameterAnnotations();
			for (int i = 0; i < annotations.length; i++) {
				for (int j = 0; j < annotations[i].length; j++) {
					if(annotations[i][j] instanceof Validate){
						result = validator.validate(annotations[i][j], args[i]);
						if(!result.isValid()){
							return result;
						}
					}
				}
			}
		}
		return result;
	}
}
